package cn.tonyandmoney.warescanapp.socket

import io.reactivex.ObservableEmitter
import io.reactivex.Observer
import io.reactivex.disposables.Disposable

/**
 * Created by niantuo on 2018/2/28.
 * 这个
 */
class RxWebSocketConnectConsumer(private val observableEmitter: ObservableEmitter<Int>) : Observer<RxSocketEvent> {

    private var mDisposable: Disposable? = null

    /**
     * 接收一次，然后就取消订阅
     */
    override fun onNext(t: RxSocketEvent) {
        dispose()
        when (t.code) {
            RxSocketEvent.CODE_CONNECT_ERROR -> {
                if (!observableEmitter.isDisposed)
                    observableEmitter.onError(t.error ?: Throwable("连接错误。"))
            }
            else -> {
                observableEmitter.onNext(0)
                observableEmitter.onComplete()
            }
        }
    }

    override fun onComplete() {
        dispose()
    }

    override fun onError(e: Throwable) {
        dispose()
    }

    override fun onSubscribe(d: Disposable) {
        mDisposable = d
    }

    private fun dispose() {
        if (mDisposable?.isDisposed == false) {
            mDisposable?.dispose()
        }
    }


}